package com.keyancompany.zhongbaopingtai.activity;

import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.adapter.SortAdapter;
import com.keyancompany.zhongbaopingtai.api.FriendsAPI;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.CharacterParser;
import com.keyancompany.zhongbaopingtai.model.FriendModel;
import com.keyancompany.zhongbaopingtai.model.PinyinComparator;
import com.keyancompany.zhongbaopingtai.model.SortModel;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.utils.T;
import com.keyancompany.zhongbaopingtai.weight.CustomEditText;
import com.keyancompany.zhongbaopingtai.weight.SideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.BindString;

import static com.keyancompany.zhongbaopingtai.activity.ChatFriendActivity.BUNDLE_RES_INFO;


/**
 * 好友列表
 */
public class FriendsActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.toolbar)
    Toolbar toolbar;

    private SortAdapter adapter;

    @Bind(R.id.filter_edit)
    CustomEditText mClearEditText;

    @Bind(R.id.country_lvcountry)
    ListView sortListView;

    @Bind(R.id.dialog)
    TextView dialog;

    @Bind(R.id.sidrbar)
    SideBar sideBar;

    @BindString(R.string.friends_list_text)
    String friendTitle;

    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeRefreshLayout;

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;

    private List<FriendModel> SourceDateList;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_friends;
    }

    @Override
    protected int getMenuId() {
        return R.menu.friends_toolbar_menu;
    }

    @Override
    protected void initToolBar() {
        initToolBar(toolbar, friendTitle);
        initSwipeLayout(swipeRefreshLayout);

    }

    public void initListener() {
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });

        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
//                Toast.makeText(getApplication(), ((SortModel) adapter.getItem(position)).getName(), Toast.LENGTH_SHORT).show();
                FriendModel model = (FriendModel) adapter.getItem(position);
                Bundle bundle = new Bundle();
                bundle.putString("res", BUNDLE_RES_INFO);
                bundle.putString("userName", model.getUsername());
                bundle.putString("pid", model.getPID_());
                IntentUtils.startActivity(mContext, ChatFriendActivity.class, bundle);
            }
        });
//根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        swipeRefreshLayout.setOnRefreshListener(this);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);


                if (item != null) {
                    searchView = (SearchView) item.getActionView();
                }
                if (searchView != null) {
//                    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
                    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                        @Override
                        public boolean onQueryTextSubmit(String query) {
                            T.showShort(mContext, query);
                            return false;
                        }

                        @Override
                        public boolean onQueryTextChange(String newText) {
                            T.showShort(mContext, newText);
                            return false;
                        }
                    });

                }
                return false;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.friends_toolbar_menu, menu);
        final MenuItem item = menu.findItem(R.id.action_add);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
        if (searchView != null) {
//                    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    if (TextUtils.isEmpty(query.trim())) {
                        T.showShort(mContext, getString(R.string.text_is_null));
                        return false;
                    }
                    IntentUtils.startActivity(mContext, SearchFriendActivity.class, SearchFriendActivity.KEY_WORD, query.trim());
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    return false;
                }
            });

        }

        return true;
    }

    @Override
    protected void setUpViews() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();

        pinyinComparator = new PinyinComparator();

        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);


        sortListView = (ListView) findViewById(R.id.country_lvcountry);


        SourceDateList = new ArrayList<>();


        adapter = new SortAdapter(this, SourceDateList);
        sortListView.setAdapter(adapter);


        mClearEditText = (CustomEditText) findViewById(R.id.filter_edit);


        swipeRefreshLayout.post(new Thread(new Runnable() {

            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                onRefresh();
            }
        }));

        initListener();

    }

    @Override
    public void failed(String error) {
        super.failed(error);
        swipeRefreshLayout.setRefreshing(false);
        T.showShort(this, error);
    }

    @Override
    public void success(int type, String json) {
        super.success(type, json);
        swipeRefreshLayout.setRefreshing(false);
        BaseModel base = validateJson(json);
        if (base == null) return;
        if (type == FriendsAPI.FRIENDS_LIST_ALL) {
            List<FriendModel> friends = JSONArray.parseArray(base.data, FriendModel.class);

            if (!friends.isEmpty()) {
                SourceDateList.clear();
                // 根据a-z进行排序源数据
                SourceDateList.addAll(friends);
                filledData(SourceDateList);
                Collections.sort(SourceDateList, pinyinComparator);
                adapter.notifyDataSetChanged();
            }
            swipeRefreshLayout.setRefreshing(false);

        }
    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<FriendModel> filledData(List<FriendModel> date) {

        for (int i = 0; i < date.size(); i++) {
            FriendModel sortModel = date.get(i);
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(sortModel.getUsername());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
        }
        return date;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<FriendModel> filterDateList = new ArrayList<>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (FriendModel sortModel : SourceDateList) {
                String name = sortModel.getUsername();
                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    @Override
    public void onRefresh() {
        FriendsAPI.getFriendsListAll(this, null);
    }
}
